let currentStudentId = null;

// 打开新增模态框
function openAddModal() {
    const modalTitle = document.getElementById('modalTitle');
    const studentNoInput = document.getElementById('studentNo');
    const passwordInput = document.getElementById('password');

    currentStudentId = null;
    document.getElementById('studentForm').reset();
    clearFormErrors();

    modalTitle.textContent = '新增学生';
    studentNoInput.readOnly = false;
    passwordInput.placeholder = '请输入密码';

    showModal();
}

// 打开编辑模态框
function openEditModal(id) {
    const modalTitle = document.getElementById('modalTitle');
    const studentNoInput = document.getElementById('studentNo');
    const passwordInput = document.getElementById('password');

    currentStudentId = id;
    document.getElementById('studentForm').reset();
    clearFormErrors();

    modalTitle.textContent = '编辑学生';
    // studentNoInput.readOnly = false;
    passwordInput.placeholder = '留空则不修改密码';

    fetchStudentData(id)
        .then(student => {
            fillFormWithStudentData(student);
            showModal();
        })
        .catch(error => {
            showToast(error.message || '获取学生信息失败', 'error');
        });
}


// 获取学生数据
function fetchStudentData(id) {
    // ✅ 修复路径
    return fetch(`/admin/get/${id}`, { method: 'GET' })
        .then(response => {
            if (!response.ok) throw new Error('服务器响应错误');
            return response.json();
        })
        .then(data => {
            if (!data.success) throw new Error(data.message);
            return data.data;
        });
}



// 用学生数据填充表单
function fillFormWithStudentData(student) {
    document.getElementById('studentNo').value = student.studentNo;
    document.getElementById('username').value = student.username;
    document.getElementById('age').value = student.age || '';
    document.getElementById('gender').value = student.gender || '';
    document.getElementById('major').value = student.major || '';
    document.getElementById('address').value = student.address || '';
    document.getElementById('telephone').value = student.telephone || '';
    document.getElementById('status').value = student.status || '';
    // document.getElementById('classId').value = student.class_id || '';
    document.getElementById('password').value = student.password || '';
   // 班级字段修复
    const classId = student.classId !== undefined ? String(student.classId) : '';
    document.getElementById('classId').value = classId;
    // // 调试输出（确认赋值结果）
    // console.log('赋值后的班级ID:', document.getElementById('classId').value);
    // console.log('赋值后的班级名称:', document.getElementById('classId').options[
    //     document.getElementById('classId').selectedIndex
    // ].text);
    //
    // document.getElementById('password').value = student.password || '';

}

// 显示模态框
function showModal() {
    const modal = document.getElementById('modal');
    const modalContent = document.getElementById('modalContent');

    modal.classList.remove('opacity-0', 'pointer-events-none');
    setTimeout(() => {
        modalContent.classList.remove('scale-95');
        modalContent.classList.add('scale-100');
    }, 10);
}

// 关闭模态框
function closeModal() {
    const modal = document.getElementById('modal');
    const modalContent = document.getElementById('modalContent');

    modalContent.classList.remove('scale-100');
    modalContent.classList.add('scale-95');

    setTimeout(() => {
        modal.classList.add('opacity-0', 'pointer-events-none');
        resetForm();
        clearFormErrors();
    }, 300);
}

// 重置表单
function resetForm() {
    document.getElementById('studentForm').reset();
    currentStudentId = null;
    document.querySelectorAll('select').forEach(select => select.selectedIndex = 0);
}
// 添加学生
function addStudent() {
    const formData = new FormData(document.getElementById('studentForm'));
    const errors = validateForm(formData);

    if (Object.keys(errors).length > 0) {
        showErrors(errors);
        return;
    }
    const requestData = buildStudentData(formData);
    sendRequest('/admin/add', 'POST', requestData)
        .then(data => {
            handleSuccessResponse(data, '添加成功');
        })
        .catch(error => {
            handleErrorResponse(error);
        });
}

// 更新学生
function updateStudent() {
    if (!currentStudentId) {
        showToast('未选择学生', 'error');
        return;
    }

    const formData = new FormData(document.getElementById('studentForm'));
    const errors = validateForm(formData);

    if (Object.keys(errors).length > 0) {
        showErrors(errors);
        return;
    }
    const requestData = buildStudentData(formData);

    sendRequest(`/admin/update/${currentStudentId}`, 'PUT', requestData)
        .then(data => {
            handleSuccessResponse(data, '更新成功');
        })
        .catch(error => {
            handleErrorResponse(error);
        });
}


// 构建学生数据对象
function buildStudentData(formData) {
    return {
        student_no: formData.get('studentNo'),
        username: formData.get('username'),
        age: formData.get('age') || null,
        gender: formData.get('gender') || null,
        major: formData.get('major') || null,
        address: formData.get('address') || null,
        telephone: formData.get('telephone') || null,
        status: formData.get('status') || null,
        class_id: formData.get('classId') || null,
        password: formData.get('password')
    };
}
// 发送HTTP请求
function sendRequest(url, method, data) {
    const btn = document.getElementById('saveButton');
    const originalText = btn.innerHTML;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 提交中...';
    btn.disabled = true;

    return fetch(url, {
        method: method,
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) throw response.json();
        return response.json();
    })
    .finally(() => {
        btn.innerHTML = originalText;
        btn.disabled = false;
    });
}
// 处理成功响应
function handleSuccessResponse(data, defaultMessage) {
    closeModal();
    showToast(data.message || defaultMessage, 'success');
    setTimeout(() => window.location.reload(), 1500);
}
// 处理错误响应
function handleErrorResponse(error) {
    error.then ? error.then(err => {
        showToast(err.message || '操作失败', 'error');
        if (err.error === 'student_no_exists') {
            document.getElementById('studentNoError').textContent = '该学号已存在';
        }
    }) : showToast(error.message || '网络请求失败', 'error');
}
// 删除学生
function deleteStudent(id) {
    if (!confirm('确认删除该学生？此操作不可恢复')) return;
    const btn = event.target.closest('button');
    const originalText = btn.innerHTML;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 删除中...';
    btn.disabled = true;
    fetch(`/admin/delete/${id}`, { method: 'DELETE' })
        .then(response => {
            if (!response.ok) throw response.json();
            return response.json();
        })
        .then(data => {
            if (data.success) {
                showToast(data.message, 'success');
                removeStudentFromTable(id);
            } else {
                showToast(data.message, 'error');
            }
        })
        .catch(error => {
            console.error('删除失败:', error);
            showToast(error.message || '网络请求失败，请重试', 'error');
        })
        .finally(() => {
            btn.innerHTML = originalText;
            btn.disabled = false;
        });
}
// 从表格中移除学生行
function removeStudentFromTable(id) {
    const row = document.querySelector(`[data-id="${id}"]`);
    if (row) {
        row.classList.add('opacity-0', 'scale-95');
        setTimeout(() => row.remove(), 300);
    } else {
        window.location.reload();
    }
}
// 保存按钮点击事件处理（根据当前状态决定是添加还是更新）
function handleSaveButton() {
    currentStudentId ? updateStudent() : addStudent();
}
// 表单验证
function validateForm(formData) {
    const errors = {};
    // 必选字段验证
    if (!formData.get('studentNo') && !currentStudentId) errors.studentNo = '学号不能为空';
    if (!formData.get('username')) errors.username = '姓名不能为空';
    if (!formData.get('classId')) errors.classId = '请选择班级';
    if (!formData.get('status')) errors.status = '请选择学籍状态';
    if (!currentStudentId && !formData.get('password')) errors.password = '密码不能为空';

    // 数值字段验证
    const age = formData.get('age');
    if (age && (!/^\d+$/.test(age) || parseInt(age) < 14 || parseInt(age) > 60)) {
        errors.age = '年龄需为14-60之间的整数';
    }

    // 格式验证
    const telephone = formData.get('telephone');
    if (telephone && !/^1[3-9]\d{9}$/.test(telephone)) {
        errors.telephone = '请输入有效的11位手机号码';
    }

    // 密码长度验证
    const password = formData.get('password');
    if (password && password.length < 6) {
        errors.password = '密码长度至少6位';
    }

    return errors;
}
// 显示错误信息
function showErrors(errors) {
    clearFormErrors();
    Object.entries(errors).forEach(([field, msg]) => {
        const errorEl = document.getElementById(`${field}Error`);
        const inputEl = document.getElementById(field);
        if (errorEl) {
            errorEl.textContent = msg;
            errorEl.classList.remove('hidden');
        }
        if (inputEl) inputEl.classList.add('border-red-500');
    });
}

// 清除错误信息
function clearFormErrors() {
    document.querySelectorAll('[id$="Error"]').forEach(el => {
        el.textContent = '';
        el.classList.add('hidden');
    });
    document.querySelectorAll('input, select').forEach(el =>
        el.classList.remove('border-red-500')
    );
}
<!-- 提示消息 -->
function showToast(message, type = 'info') {
    const toast = document.createElement('div');
    toast.className = `fixed top-0 right-0 p-3 rounded-lg shadow-lg z-[9999] ${
        type === 'success' ? 'bg-green-500 text-white' :
        type === 'error' ? 'bg-red-500 text-white' :
        'bg-blue-500 text-white'
    } animate-fade-in-out transition-all duration-300 transform translate-x-full`;
    toast.innerHTML = `
        <i class="fa ${type === 'success' ? 'fa-check' : 'fa-exclamation'} mr-2"></i>
        ${message}
    `;
    document.body.appendChild(toast);

    // 触发动画
    setTimeout(() => toast.classList.remove('translate-x-full'), 10);

    setTimeout(() => {
        toast.classList.add('translate-x-full');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

document.addEventListener('DOMContentLoaded', () => {
    const searchForm = document.getElementById('searchForm');

    // 表单提交前处理
    searchForm.addEventListener('submit', (e) => {
        // 如果关键词为空，自动提交空搜索（获取全部结果）
        const searchInput = searchForm.querySelector('input[name="keyword"]');
        if (!searchInput.value.trim()) {
            searchInput.value = ''; // 确保空字符串提交
        }

        // 可选：添加 loading 状态（保持原有样式）
        const searchIcon = searchForm.querySelector('i.fa-search');
        searchIcon.classList.remove('fa-search');
        searchIcon.classList.add('fa-spinner', 'fa-spin');

        // 提交后页面刷新，无需手动恢复图标样式
    });
});

// 初始化：绑定事件监听器
document.addEventListener('DOMContentLoaded', () => {
    // 绑定保存按钮事件
    document.getElementById('saveButton').addEventListener('click', handleSaveButton);

    // 密码显示/隐藏切换
    document.querySelectorAll('.toggle-password').forEach(btn => {
        btn.addEventListener('click', () => {
            const input = btn.closest('.relative').querySelector('input');
            const icon = btn.querySelector('i');
            input.type = input.type === 'password' ? 'text' : 'password';
            icon.classList.toggle('fa-eye-slash');
            icon.classList.toggle('fa-eye');
        });
    });

    // 实时验证（输入时清除对应错误）
    document.querySelectorAll('#studentForm input, #studentForm select').forEach(field => {
        field.addEventListener('input', () => {
            const errorEl = document.getElementById(`${field.id}Error`);
            if (errorEl && !errorEl.classList.contains('hidden')) {
                const formData = new FormData(document.getElementById('studentForm'));
                if (!validateForm(formData)[field.id]) {
                    errorEl.classList.add('hidden');
                    field.classList.remove('border-red-500');
                }
            }
        });
    });
});
function confirmDelete(id, btn) {
    if (!confirm('确认删除该学生？此操作不可恢复')) return;
    deleteStudent(id, btn);
}